package cn.song.logread.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IP工具类
 *
 * @author SongRenShuo
 * @date 2024-01-26
 */
@Slf4j
public class IpUtil {

    /**
     * 获取(用户端)IP地址
     *
     * @param request 请求
     * @date 2025/03/21
     * @return {@link String }
     * @author SongRenShuo
     */
    public static String getIpAddr(HttpServletRequest request) {
        try {
            String ip = request.getHeader("x-forwarded-for");
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                ip = ip.split(",")[0];
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            System.out.println("获取客户端ip: " + ip);
            String replace = ip.replace(":", ".");
            if (replace.contains("0:0:0:0:0:0:0:1") || replace.contains("localhost")) {
                replace = "127.0.0.1";
            }
            return replace;
        } catch (Exception e) {
            log.error("获取客户端ip异常", e);
            return "";
        }
    }

    /**
     * IP 白名单验证 - 支持通配符
     *
     * @param ip IP 地址
     * @param ipWhitelistListStr IP 白名单列表字符串，英文逗号分割
     * @date 2025/03/21
     * @return boolean
     * @author SongRenShuo
     */
    public static boolean ipWhitelistVerify(String ip, String ipWhitelistListStr) {

        return ipWhitelistVerify(ip, Arrays.stream(ipWhitelistListStr.split(",")).collect(Collectors.toList()));
    }

    /**
     * IP 白名单验证 - 支持通配符
     *
     * @param ip IP 地址
     * @param ipWhitelistList IP 白名单列表
     * @date 2025/03/21
     * @return boolean
     * @author SongRenShuo
     */
    public static boolean ipWhitelistVerify(String ip, List<String> ipWhitelistList) {
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            return false;
        }
        if (ipWhitelistList.isEmpty()) {
            return true;
        }

        return ipWhitelistList.stream().anyMatch(ipWhitelist -> {
            String regex = ipWhitelist.replace(".", "\\.").replace("*", ".*").replace("[","").replace("]","");
            return ip.matches(regex);
        });
    }

    public static void main(String[] args) {
        List<String> ipWhitelistListCache = Arrays.asList("127.0.0.1", "192.168.1.*");
        String ipWhitelistListCacheStr = "[\"127.0.0.1\",\"192.168.1.*\"]";
        String ip = "192.168.2.4";
        System.out.println(ipWhitelistVerify(ip, ipWhitelistListCache));
        System.out.println(ipWhitelistVerify(ip, ipWhitelistListCacheStr));
    }

}
